import React, { useState } from 'react';
import { Modal, Form, Input, message } from 'antd';
import { connect } from 'dva';
import { updateUserPwd } from '@/services/login';
import { jsEncodePwd } from '@/utils/utils';

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

function checkPwd(rule, value, callback) {
  if (value === undefined) {
    callback();
    return;
  }
  let hasNumber = false;
  let hasLowcase = false;
  let hasSpecLetter = false;
  let hasUppercase = false;
  const missInfo = [];
  const specialReg = new RegExp(
    '[`\\~\\!@#\\$%^&\\*\\(\\)\\-_+=\\[\\{\\]\\}\\|\\\\:;\'"/\\?,\\.<>]'
  );
  if (/[0-9]/.test(value)) {
    hasNumber = true;
  } else {
    missInfo.push('数字');
  }
  if (/[a-z]/.test(value)) {
    hasLowcase = true;
  } else {
    missInfo.push('小写字母');
  }
  if (/[A-Z]/.test(value)) {
    hasUppercase = true;
  } else {
    missInfo.push('大写字母');
  }
  if (specialReg.test(value)) {
    hasSpecLetter = true;
  } else {
    missInfo.push('特殊字符');
  }
  if (value.length < 6 || value.length > 20) {
    missInfo.push('长度必须是6-20位');
  }

  if (!hasNumber || !hasLowcase || !hasSpecLetter || !hasUppercase) {
    callback(`缺少：${missInfo.join(',')}`);
  } else {
    callback();
  }
}

function ChangePassword({ visible, close, form, dispatch, userCode, onSuccess }) {
  const [loading, setLoading] = useState(false);

  function compareToFirstPassword(rule, value, callback) {
    if (value && value !== form.getFieldValue('newPwd')) {
      callback('两次输入的密码不一致');
    } else {
      callback();
    }
  }

  function handleSubmit(e) {
    e.preventDefault();

    form.validateFields((err, values) => {
      if (!err) {
        const { pwd, cfmPwd } = values;
        const formValues = {
          // userId: this.userId,
          userCode,
          password: jsEncodePwd(pwd),
          newPwd: jsEncodePwd(cfmPwd),
          // pwdEffectDays: this.options.pwdEffectDays
        };
        setLoading(true);
        updateUserPwd(formValues)
          .then(response => {
            if (response.resultCode === '0000') {
              close();
              if (onSuccess) {
                message.success('密码修改成功');
                onSuccess();
              } else {
                Modal.success({
                  title: '修改成功',
                  content: '3秒后将自动退出，重新登录',
                  onOk: () => {
                    dispatch({
                      type: 'login/logout',
                    });
                  },
                });
              }
            } else {
              message.error(response.resultMsg);
            }
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  }

  return (
    <Modal
      title="修改密码"
      visible={visible}
      onOk={handleSubmit}
      onCancel={close}
      confirmLoading={loading}
      destroyOnClose
      centered
      okButtonProps={{ htmlType: 'submit' }}
    >
      <Form layout="horizontal" onSubmit={handleSubmit}>
        <Form.Item style={{ marginBottom: 16 }} label="旧密码" {...formItemLayout}>
          {form.getFieldDecorator('pwd', {
            rules: [
              {
                required: true,
                whitespace: true,
                message: '请输入旧密码',
              },
            ],
          })(<Input type="password" allowClear placeholder="旧密码" onPressEnter={handleSubmit} />)}
        </Form.Item>
        <Form.Item style={{ marginBottom: 16 }} label="新密码" {...formItemLayout}>
          {form.getFieldDecorator('newPwd', {
            rules: [
              {
                required: true,
                message: '请输入新密码',
              },
              {
                validator: checkPwd,
              },
            ],
          })(
            <Input
              type="password"
              allowClear
              onPressEnter={handleSubmit}
              placeholder="6-20位，包含数字、大小写字母和特殊字符"
            />
          )}
        </Form.Item>
        <Form.Item style={{ marginBottom: 16 }} label="确认密码" {...formItemLayout}>
          {form.getFieldDecorator('cfmPwd', {
            rules: [
              {
                required: true,
                // min: 8,
                message: '请确认你的新密码',
              },
              {
                validator: compareToFirstPassword,
              },
            ],
          })(
            <Input type="password" allowClear placeholder="确认密码" onPressEnter={handleSubmit} />
          )}
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default connect(({ login }) => ({
  login,
}))(Form.create()(ChangePassword));
